//
//  ZYXTabBar.m
//  Lottery
//  自定义tabBar控件视图 添加在自定义ZYXTabBarController上
//

#import "ZYXTabBar.h"

#import "ZYXTabBarButton.h"                     //引入自定义按钮

@interface ZYXTabBar()

/**
 *  在ZYXTabBarController控制器view视图上的
 *  自定义ZYXTabBar控件上的
 *  选中的ZYXTabBarButton 按钮
 */
@property (nonatomic,weak) UIButton *selectedButton;

@end


@implementation ZYXTabBar

/**
 *  初始化子控件
 */
-(void)layoutSubviews
{
    //设置按钮的尺寸
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    for (int i=0; i<self.subviews.count; i++) {
        ZYXTabBarButton *button = self.subviews[i];
        CGFloat buttonX = i * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
       
        //给按钮绑定tag
        button.tag = i;
    }
}

/**
 *  监听ZYXTabBar控件上按钮的点击事件
 *
 *  @param button 点击的ZYXTabBarButton按钮
 */
-(void)buttonClick:(UIButton *)button
{
    //按钮点击通知代理对象
    //代理对象.selectedIndex = button.tag;
    //点击ZYXtabBarButton对象切换对应的导航控制器
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectButtonFrom:To:)]) {
        [self.delegate tabBar:self didSelectButtonFrom:self.selectedButton.tag To:button.tag];
    }
    
    
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
}

/**
 *  创建按钮
 *
 *  @param imageName         按钮的普通状态图片
 *  @param selectedImageName 按钮的选中状态图片
 */
-(void)addTabBarButtonWithImageName:(NSString *)imageName SelectedImageName:(NSString *)selectedImageName
{
    //自定义创建按钮
    //UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    ZYXTabBarButton *button = [ZYXTabBarButton buttonWithType:UIButtonTypeCustom];
    
    //设置按钮的普通图片
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    //设置按钮的选中图片
    [button setBackgroundImage:[UIImage imageNamed:selectedImageName] forState:UIControlStateSelected];
    
    //长按按钮时图片不显示高亮效果
    //button.adjustsImageWhenHighlighted = NO;
    
    //将button添加到自定义ZYXTabBar上显示出来
    [self addSubview:button];
    
    //监听按钮点击事件    UIControlEventTouchDown 手指一按下去就触发按钮事件
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    //默认选中第0个按钮
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}

@end
